var express = require('express');
var router = express.Router();
let { gomodel, address, userModel, goodcarmodel } = require('../../model/model')
let multiparty = require('multiparty')

router.post('/addaddress', async (req, res) => {
  if (req.body._id) {
    await address.updateOne({ _id: req.body._id }, req.body)
    res.send({
      code: 200
    })
  } else {
    if (req.body.isDefault === false) {
      address.create(req.body)
      res.send({
        code: 200
      })
    }
    if (req.body.isDefault === true) {
      await address.updateMany({ isDefault: true }, { isDefault: false })
      address.create(req.body)
      res.send({
        code: 200
      })
    }
  }
})

router.get('/getaddress', async (req, res) => {
  let data = await address.find();
  res.send({
    code: 200,
    data
  })
})

router.delete('/deladdress', async (req, res) => {
  let { _id } = req.query
  await address.deleteOne({ _id })
  res.send({
    code: 200
  })
})

router.put('/editphone', async (req, res) => {
  await userModel.updateOne({ _id: req.body._id }, { phone: req.body.phone })
  res.send({
    code: 200
  })
})

router.post('/upload', async (req, res) => {
  let form = new multiparty.Form();
  form.uploadDir = 'upload';

  form.parse(req, async (err, fields, files) => {
    if (err) {
      return res.status(400).send({ code: 400, message: '文件解析失败' });
    }

    try {
      const userId = fields.userId[0]; // 获取 userId
      const avatarPath = 'http://127.0.0.1:3000/' + files.avatar[0].path; // 获取头像文件路径

      // 更新用户头像路径
      await userModel.updateOne({ _id: userId }, { avatar: avatarPath });
      let data = await userModel.findOne({ _id: userId })

      // 返回成功响应
      return res.send({
        code: 200,
        message: '上传成功',
        data
      });
    } catch (error) {
      console.error('更新数据库失败:', error);
      return res.status(500).send({ code: 500, message: '服务器内部错误' });
    }
  });
});

// 签到接口
router.post('/addsign', async (req, res) => {
  // console.log(req.body);
  const { _id, signedDates } = req.body;

  if (!_id || !signedDates || !Array.isArray(signedDates)) {
    return res.status(400).send({ code: 400, message: '缺少必要参数或参数格式错误' });
  }

  try {
    // 对每个签到日期使用 $addToSet 避免重复
    const updateResult = await userModel.updateOne(
      { _id: _id },
      { $addToSet: { signedDates: { $each: signedDates } } } // 确保不重复添加签到
    );

    // 检查是否更新成功
    if (updateResult.modifiedCount === 0) {
      return res.status(400).send({ code: 400, message: '签到日期未更新，可能已存在' });
    }

    res.send({ code: 200, message: '签到成功' });
  } catch (error) {
    console.error(error);
    res.status(500).send({ code: 500, message: '服务器错误' });
  }
});

// 获取签到接口
router.get('/getsign', async (req, res) => {

  const _id = req.query._id; // 通过查询参数获取用户 ID

  if (!_id) {
    return res.status(400).send({ code: 400, message: '缺少必要参数' });
  }

  try {
    const data = await userModel.findOne({ _id: _id }, { signedDates: 1 }); // 仅返回 signedDates
    if (!data) {
      return res.status(404).send({ code: 404, message: '用户未找到' });
    }

    res.send({ code: 200, data: data.signedDates });
  } catch (error) {
    console.error(error);
    res.status(500).send({ code: 500, message: '服务器错误' });
  }
});

// 获取收藏接口
router.get('/getgomodel', async (req, res) => {
  let data = await gomodel.find()
  res.send({
    code: 200,
    data
  })
})

router.get('/getgoodcar', async (req, res) => {
  let data = await goodcarmodel.find()
  res.send({
    code: 200,
    data
  })
})

router.delete('/delgoodcar', async (req, res) => {
  await goodcarmodel.deleteOne({ _id: req.query._id })
  res.send({
    code: 200
  })
})

module.exports = router;
